import re

from django_redis import get_redis_connection
from redis import StrictRedis
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from users.models import User


class CreateUserSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(label="确认密码", write_only=True)
    sms_code = serializers.CharField(label="短信验证码", write_only=True)
    allow = serializers.BooleanField(label="同意协议", write_only=True)
    token = serializers.CharField(label='登录状态token', read_only=True)

    def create(self, validated_data):
        user = User.objects.create_user(
            username=validated_data.get('username'),
            password=validated_data.get('password'),
            mobile=validated_data.get('mobile'))
        # 注册成功自动登录，需要生成jwt并返回给客户端
        # 导包： from rest_framework_jwt.settings import api_settings
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        # {'user_id': 12, 'email': '', 'username': '13600000000', 'exp': 1539048426}
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token  # 生成的jwt 序列化返回
        return user

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'password', 'password2', 'sms_code', 'allow', 'token')
        extra_kwargs = {
            'username': {
                'max_length': 20,
                'min_length': 5,
                'error_messages': {
                    'min_length': '进允许5-20个字符的用户名',
                    'mix_length': '进允许5-20个字符的用户名'
            }
        },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'mix_length': '仅允许8-20个字符的密码'
                }
            }
        }

        def validate_mobile(self, value):
            """验证手机号"""
            if not re.match(r'^1[35789]\d{9}/$', value):
                raise serializers.ValidationError('手机号格式错误')
            return value

        def validate_allow(self, value):
            """验证是否同意协议"""
            if not value:
                raise serializers.ValidationError('请同意用户协议')
            return value

        def validate(self, attrs):
            if attrs['password'] != attrs['password2']:
                raise serializers.ValidationError('两次密码不一样')
            redis_dict = get_redis_connection('sms_codes')  # type:StrictRedis
            mobile = attrs['mobile']
            real_sms_code = redis_dict.get('sms_%s' % mobile)
            sms_code = attrs['sms_code']
            if real_sms_code is None:
                raise serializers.ValidationError('短信验证码已经无效')
            if sms_code != real_sms_code.decode():
                raise serializers.ValidationError('短信验证码输入错误')
            return attrs




